package com.jxc.action.xsgl;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;

import com.jxc.action.BaseAction;
import com.jxc.model.po.BasicArgument;
import com.jxc.model.vo.Json;
import com.jxc.model.vo.SessionInfo;
import com.jxc.model.vo.VAuditRecord;
import com.jxc.model.vo.VCustomerType;
import com.jxc.model.vo.VMemberType;
import com.jxc.model.vo.VRepertory;
import com.jxc.model.vo.VSaleReturnlist;
import com.jxc.model.vo.VSalelist;
import com.jxc.model.vo.VSerial;
import com.jxc.model.vo.VUser;
import com.jxc.service.AuditRecordServiceI;
import com.jxc.service.BasicArgumentServiceI;
import com.jxc.service.CustomerTypeServiceI;
import com.jxc.service.MemberTypeServiceI;
import com.jxc.service.RepertoryServiceI;
import com.jxc.service.SaleReturnlistServiceI;
import com.jxc.service.SalelistServiceI;
import com.jxc.service.SerialService;
import com.jxc.service.UserServiceI;
import com.jxc.util.Constants;
import com.jxc.util.ExceptionUtil;
import com.jxc.util.ResourceUtil;
import com.jxc.util.SerialUtils;

/**
 * 
 * @author Tino
 * 
 */
@Namespace("/xsgl")
public class IndexAction extends BaseAction {
	private final static Logger logger = Logger.getLogger(IndexAction.class);

	private String rid;
	private Date beginDate;
	private Date endDate;

	@Autowired
	private UserServiceI userService;
	@Autowired
	private RepertoryServiceI repertoryService;
	@Autowired
	private MemberTypeServiceI memberTypeService;
	@Autowired
	private CustomerTypeServiceI customerTypeService;
	@Autowired
	private AuditRecordServiceI auditRecordService;
	@Autowired
	private SalelistServiceI salelistService;
	@Autowired
	private SerialService serialService;
	@Autowired
	private SaleReturnlistServiceI saleReturnlistService;
	@Autowired
	private BasicArgumentServiceI basicArumentService;

	@Action(value = "sale", results = { @Result(name = "sale", location = "/sale/sale.jsp") })
	public String sale() {
		SessionInfo sessionInfo = (SessionInfo) ServletActionContext.getRequest().getSession().getAttribute(ResourceUtil.getSessionInfoName());
		VUser vuser = userService.get(sessionInfo.getUserId());

		/*
		 * --------------------------------------------------------------------------------------
		 * 出货仓库下拉框数据
		 * --------------------------------------------------------------------------------------
		 */
		List<VRepertory> vrepertories = new ArrayList<VRepertory>();
		if (vuser.getReid() != null) {
			VRepertory vrepertory = new VRepertory();
			vrepertory.setId(vuser.getReid());
			vrepertory.setName(vuser.getRename());
			vrepertories.add(vrepertory);
			
		} else {
			VRepertory vrepertory = new VRepertory();
			vrepertory.setUid(sessionInfo.getUserId());
			vrepertories = repertoryService.list(vrepertory);
		}
		this.getRequest().setAttribute("VRepertories", vrepertories);

		/*
		 * --------------------------------------------------------------------------------------
		 * 营业员下拉框数据
		 * --------------------------------------------------------------------------------------
		 */
		List<VUser> vusers = new ArrayList<VUser>();
		VUser vUser = new VUser();
		if (vrepertories != null && vrepertories.size() > 0) {
			for (VRepertory vre : vrepertories) {
				vUser.setReid(vre.getId());
				vusers.addAll(userService.combobox(vUser));
			}
		}
		if (vrepertories.size() > 1)
			vusers.add(vuser);
		this.getRequest().setAttribute("VUsers", vusers);

		/*
		 * --------------------------------------------------------------------------------------
		 * 会员类型下拉框数据
		 * --------------------------------------------------------------------------------------
		 */
		List<VMemberType> vMemberTypes = new ArrayList<VMemberType>();
		VMemberType vmt = new VMemberType();
		if (vuser.getReid() != null) {
			VRepertory vr = new VRepertory();
			vr.setId(vuser.getReid());
			List<VRepertory> vrs = repertoryService.list(vr);
			if (vrs.size() > 0) {
				vmt.setUid(vrs.get(0).getUid());
				vMemberTypes = memberTypeService.combobox(vmt);
			}
		} else {
			vmt.setUid(vuser.getId());
			vMemberTypes = memberTypeService.combobox(vmt);
		}
		this.getRequest().setAttribute("VMemberTypes", vMemberTypes);

		/*
		 * --------------------------------------------------------------------------------------
		 * 新增会员客户类型下拉框数据
		 * --------------------------------------------------------------------------------------
		 */
		List<VCustomerType> vcts = new ArrayList<VCustomerType>();
		VCustomerType vct = new VCustomerType();
		if (vrepertories != null && vrepertories.size() > 0) {
			for (VRepertory vre : vrepertories) {
				vct.setRid(vre.getId());
				vcts.addAll(customerTypeService.combobox(vct));
			}
		}
		this.getRequest().setAttribute("VCustomerTypes", vcts);

//		/*
//		 * --------------------------------------------------------------------------------------
//		 * 销售单号
//		 * --------------------------------------------------------------------------------------
//		 */
//		VSerial ser = new VSerial();
////		ser.setRid(rid);
//		ser.setType("XS");
//		this.getRequest().setAttribute("serial",serialService.getAll(ser));
		
		/*
		 * --------------------------------------------------------------------------------------
		 * 会员编号
		 * --------------------------------------------------------------------------------------
		 */
//		this.getRequest().setAttribute("memSerial", SerialUtils.serial("HY"));
		return "sale";
	}

	@Action(value = "saleReturn", results = { @Result(name = "saleReturn", location = "/sale/saleReturn.jsp") })
	public String saleReturn() {
		this.getRequest().setAttribute("serial", SerialUtils.serial("XSTH"));
		return "saleReturn";
	}

	@Action(value = "amount", results = { @Result(name = "amount", location = "/sale/amount.jsp") })
	public String amount() {
		return "amount";
	}

	@Action(value = "member", results = { @Result(name = "member", location = "/sale/member.jsp") })
	public String member() {
		return "member";
	}
	
	
	//日请结算
	@Action(value = "settlement", results = { @Result(name = "settlement", location = "/sale/settlement.jsp") })
	public String settlement() {
		try{
		SessionInfo sessionInfo = (SessionInfo) ServletActionContext.getRequest().getSession().getAttribute(ResourceUtil.getSessionInfoName());
		VUser vuser = userService.get(sessionInfo.getUserId());

		/*
		 * --------------------------------------------------------------------------------------
		 * 仓库下拉框数据
		 * --------------------------------------------------------------------------------------
		 */
		List<VRepertory> vrepertories = new ArrayList<VRepertory>();
		if (vuser.getReid() != null) {
			VRepertory vrepertory = new VRepertory();
			vrepertory.setId(vuser.getReid());
			vrepertory.setName(vuser.getRename());
			vrepertories.add(vrepertory);
		} else {
			VRepertory vrepertory = new VRepertory();
			vrepertory.setUid(sessionInfo.getUserId());
			vrepertories = repertoryService.list(vrepertory);
		}
		this.getRequest().setAttribute("VRepertories", vrepertories);

		/*
		 * --------------------------------------------------------------------------------------
		 * 查询最近一条结算记录
		 * --------------------------------------------------------------------------------------
		 */
		Long rid = vuser.getReid() == null ? vrepertories.get(0).getId() : vuser.getReid();
		this.getRequest().setAttribute("rid", rid);

		VAuditRecord param = new VAuditRecord();
		param.setRid(rid);
		param.setOrder("desc");
		param.setSort("endAudit");
		List<VAuditRecord> vars = auditRecordService.combobox(param);
		Date beginDate = null;
		if (vars.size() > 0) {
			VAuditRecord var = vars.get(0);
			this.getRequest().setAttribute("EndAudit", new SimpleDateFormat("yyyy年MM月dd日").format(var.getEndAudit()));
			Calendar cal = Calendar.getInstance();
			cal.setTime(var.getEndAudit());
			cal.add(Calendar.DAY_OF_MONTH, 1);
			beginDate = cal.getTime();
		}
		this.getRequest().setAttribute("BeginAudit", beginDate == null ? "" : new SimpleDateFormat("yyyy-MM-dd").format(beginDate));

		Double total = 0.0;

		VSalelist para = new VSalelist();
		para.setRid(rid);
		para.setBeginDate(beginDate);
		List<VSalelist> vsls = salelistService.combobox(para);
		if (vsls.size() > 0) {
			for (VSalelist vsl : vsls) {
				if (vsl.getPointNum() == null) {
					total += vsl.getTotal();
				} else {
					BasicArgument ba = this.basicArumentService.getBasricArgumentByKey(rid, Constants.INTEGRAL_CONVERSION_RATIO);
					Double point=0d;
					
					if(vsl!=null&&ba!=null){
						point = (vsl.getPointNum() / Double.parseDouble(ba.getArgValue()));
					}
					
					if (point < vsl.getTotal()) {
						total += (vsl.getTotal() - point);
					}
				}
			}

			VSaleReturnlist par = new VSaleReturnlist();
			par.setRid(rid);
			par.setBeginDate(beginDate);
			List<VSaleReturnlist> vsrls = saleReturnlistService.combobox(par);
			if (vsrls.size() > 0) {
				for (VSaleReturnlist vsrl : vsrls) {
					total -= vsrl.getRealReturn();
				}
			}
		}
		DecimalFormat format = new DecimalFormat("0.00");
		this.getRequest().setAttribute("total", format.format(total));
		}catch (Exception e) {
			e.printStackTrace();
		}
		
		return "settlement";
	}

	@Action(value = "salelist", results = { @Result(name = "salelist", location = "/sale/salelist.jsp") })
	public String salelist() {
		SessionInfo sessionInfo = (SessionInfo) ServletActionContext.getRequest().getSession().getAttribute(ResourceUtil.getSessionInfoName());
		VUser vuser = userService.get(sessionInfo.getUserId());

		/*
		 * --------------------------------------------------------------------------------------
		 * 出货仓库下拉框数据
		 * --------------------------------------------------------------------------------------
		 */
		List<VRepertory> vrepertories = new ArrayList<VRepertory>();
		if (vuser.getReid() != null) {
			VRepertory vrepertory = new VRepertory();
			vrepertory.setId(vuser.getReid());
			vrepertory.setName(vuser.getRename());
			vrepertories.add(vrepertory);
		} else {
			VRepertory vrepertory = new VRepertory();
			vrepertory.setUid(sessionInfo.getUserId());
			vrepertories = repertoryService.list(vrepertory);
		}
		this.getRequest().setAttribute("VRepertories", vrepertories);

		/*
		 * --------------------------------------------------------------------------------------
		 * 营业员下拉框数据
		 * --------------------------------------------------------------------------------------
		 */
		List<VUser> vusers = new ArrayList<VUser>();
		VUser vUser = new VUser();
		if (vrepertories != null && vrepertories.size() > 0) {
			for (VRepertory vre : vrepertories) {
				vUser.setReid(vre.getId());
				vusers.addAll(userService.combobox(vUser));
			}
		}
		if (vrepertories.size() > 1)
			vusers.add(vuser);
		this.getRequest().setAttribute("VUsers", vusers);

		return "salelist";
	}

	//销售结算
	@Action(value = "statistic")
	public void noAuth_statistic() {
		Json j = new Json();
		try {
			Double total = 0.0;

			if (beginDate != null) {
				String beginDateStr = new SimpleDateFormat("yyyy-MM-dd").format(beginDate);
				beginDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(beginDateStr + " 00:00:00");
			}

			VAuditRecord param = new VAuditRecord();
			param.setRid(Long.parseLong(rid));
			param.setOrder("desc");
			param.setSort("endAudit");
			List<VAuditRecord> vars = auditRecordService.combobox(param);
			if (vars.size() > 0) {
				VAuditRecord var = vars.get(0);
				this.getRequest().setAttribute("EndAudit", new SimpleDateFormat("yyyy年MM月dd日").format(var.getEndAudit()));
				Calendar cal = Calendar.getInstance();
				cal.setTime(var.getEndAudit());
				cal.add(Calendar.DAY_OF_MONTH, 1);
				Date systemBeginDate = cal.getTime();

				if (beginDate == null) {
					j.setMsg("结算开始时间不能为空！");
					super.writeJson(j);
					return;
				}

				if (systemBeginDate.after(beginDate)) {
					j.setMsg("结算开始时间早于或等于上次结算时间！");
					super.writeJson(j);
					return;
				}
			}

			if (endDate != null) {
				String endDateStr = new SimpleDateFormat("yyyy-MM-dd").format(endDate);
				endDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(endDateStr + " 23:59:59");
			}

			if (endDate.before(beginDate)) {
				j.setMsg("结算结束时间早于结算开始时间！");
				super.writeJson(j);
				return;
			}

			VSalelist para = new VSalelist();
			para.setRid(Long.parseLong(rid));
			para.setBeginDate(beginDate);
			para.setEndDate(endDate);
			List<VSalelist> vsls = salelistService.combobox(para);
			if (vsls.size() > 0) {
				for (VSalelist vsl : vsls) {
					if (vsl.getPointNum() == null) {
						total += vsl.getTotal();
					} else {
						BasicArgument ba = this.basicArumentService.getBasricArgumentByKey(Long.parseLong(rid), Constants.INTEGRAL_CONVERSION_RATIO);
						
						Double point =0d;
						if(vsl!=null&&ba!=null){
							point = (vsl.getPointNum() / Double.parseDouble(ba.getArgValue()));
						}
						if (point < vsl.getTotal()) {
							total += (vsl.getTotal() - point);
						}
					}
				}

				VSaleReturnlist par = new VSaleReturnlist();
				par.setRid(Long.parseLong(rid));
				par.setBeginDate(beginDate);
				par.setEndDate(endDate);
				List<VSaleReturnlist> vsrls = saleReturnlistService.combobox(par);
				System.out.println(total);
				if (vsrls.size() > 0) {
					for (VSaleReturnlist vsrl : vsrls) {
						System.out.println(vsrl.getRealReturn());
						if(vsrl.getRealReturn()==null)
							vsrl.setRealReturn(0d);
						total -= vsrl.getRealReturn();
					}
				}
				DecimalFormat format = new DecimalFormat("0.00");
				j.setObj(format.format(total));
			} else {
				j.setObj(0.0);
			}
		} catch (Exception e) {
			logger.info(ExceptionUtil.getExceptionMessage(e));
			j.setMsg("统计异常！");
		}
		super.writeJson(j);
	}
	
	@Action(value = "saleReturnlist", results = { @Result(name = "saleReturnlist", location = "/sale/saleReturnlist.jsp") })
	public String saleReturnlist() {
		SessionInfo sessionInfo = (SessionInfo) ServletActionContext.getRequest().getSession().getAttribute(ResourceUtil.getSessionInfoName());
		VUser vuser = userService.get(sessionInfo.getUserId());

		/*
		 * --------------------------------------------------------------------------------------
		 * 出货仓库下拉框数据
		 * --------------------------------------------------------------------------------------
		 */
		List<VRepertory> vrepertories = new ArrayList<VRepertory>();
		if (vuser.getReid() != null) {
			VRepertory vrepertory = new VRepertory();
			vrepertory.setId(vuser.getReid());
			vrepertory.setName(vuser.getRename());
			vrepertories.add(vrepertory);
		} else {
			VRepertory vrepertory = new VRepertory();
			vrepertory.setUid(sessionInfo.getUserId());
			vrepertories = repertoryService.list(vrepertory);
		}
		this.getRequest().setAttribute("VRepertories", vrepertories);

		/*
		 * --------------------------------------------------------------------------------------
		 * 营业员下拉框数据
		 * --------------------------------------------------------------------------------------
		 */
		List<VUser> vusers = new ArrayList<VUser>();
		VUser vUser = new VUser();
		if (vrepertories != null && vrepertories.size() > 0) {
			for (VRepertory vre : vrepertories) {
				vUser.setReid(vre.getId());
				vusers.addAll(userService.combobox(vUser));
			}
		}
		if (vrepertories.size() > 1)
			vusers.add(vuser);
		this.getRequest().setAttribute("VUsers", vusers);

		return "saleReturnlist";
	}


	public String getRid() {
		return rid;
	}

	public void setRid(String rid) {
		this.rid = rid;
	}

	public Date getBeginDate() {
		return beginDate;
	}

	public void setBeginDate(Date beginDate) {
		this.beginDate = beginDate;
	}

	public Date getEndDate() {
		return endDate;
	}

	public void setEndDate(Date endDate) {
		this.endDate = endDate;
	}

}
